import axios from "axios";
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'
import { useUserStore } from '@/stores/user'
import router from '@/router'

const instance = axios.create({
  baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
  timeout: 5000,
  headers: { 'X-Custom-Header': 'foobar' }
});

// 添加请求拦截器
instance.interceptors.request.use(function (config) {
  // 在发送请求之前做些什么
  const userStore = useUserStore()
  const token = userStore.userInfo.token

  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }

  return config;
}, function (error) {
  // 对请求错误做些什么

  return Promise.reject(error);
});

// 添加响应拦截器

instance.interceptors.response.use(res => res.data, e => {


  return Promise.reject(e);

});



// instance.interceptors.response.use(res => res.data, e => {

//   const userStore = useUserStore()
//   ElMessage.warning(e.response.data.message)
//   if (e.response.status === 401) {
//     userStore.clearUserInfo()
//     router.push('/login')
//   }
//   return Promise.reject(e);

// });



export default instance